package com.xxx.car.web;

/**
 * Created by youxiaojia on 2017/6/14.
 */

import com.xxx.car.service.CommonService;
import com.xxx.common.base.vo.APIResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@Controller
@RequestMapping("/upload")
public class FileUploadController {

    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
    //文件存储绝对路径
    @Value("${upload.filePath}")
    private String filePath;

    private final ResourceLoader resourceLoader;

    @Autowired
    CommonService commonService;

    @Autowired
    public FileUploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/")
    public String provideUploadInfo(Model model) throws IOException {

        model.addAttribute("files", Files.walk(Paths.get(filePath))
                .filter(path -> !path.equals(Paths.get(filePath)))
                .map(path -> Paths.get(filePath).relativize(path))
                .map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    //显示图片的方法关键 匹配路径像 localhost:40000/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(filePath, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    //上传的方法
    @RequestMapping(method = RequestMethod.POST, value = "/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes, HttpServletRequest request) {
        System.out.println(request.getParameter("member"));
        if (!file.isEmpty()) {
            try {
                Files.copy(file.getInputStream(), Paths.get(filePath, file.getOriginalFilename()));
                redirectAttributes.addFlashAttribute("message",
                        "You successfully uploaded " + file.getOriginalFilename() + "!");
            } catch (IOException | RuntimeException e) {
                redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
        }
        return "redirect:/upload/";
    }

    //app上传图片的方法
    @RequestMapping(method = RequestMethod.POST, value = "/icon")
    public APIResponse appHandleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {
            try {
                Files.copy(file.getInputStream(), Paths.get(filePath, file.getOriginalFilename()));

                return APIResponse.returnSuccess(file.getOriginalFilename());
            } catch (Exception e) {
                return APIResponse.returnFail("请上传合适大小图片");
            }
        } else {
            return APIResponse.returnFail("请选择图片");
        }
    }

	/**
     * editor 图片上传
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/editor")
    public @ResponseBody String uploadImageByEditor(@RequestParam("filedata") MultipartFile file, HttpServletRequest request) {
        String message = "";
        String err = "";
        String msg = "/upload/";
        if (!file.isEmpty()) {
            try {
                String fileName = commonService.uploadFile(file);
                msg = msg + fileName;
                message = "{\"err\":\"" + err + "\",\"msg\":\"" + msg
                        + "\"}";
                err = message;
                return message;
            } catch (Exception e) {
                e.printStackTrace();
                return message;
            }
        } else {
            return message;
        }

    }


	/**
     * 编辑banner详情
     * @param editorContent
     * @param request
     * @return
     */
    @RequestMapping(value = "/editorSubmit")
    public String submitEditorForm(@RequestParam("editorContent") String editorContent, HttpServletRequest request) {
        System.out.println(editorContent);
        return "bannerList";
    }
}
